<template>
    <div class="common-layout">
        <el-row>
            <el-col :span="8">
                <el-select v-model="state.selected" class="m-2" placeholder="Select" 
                filterable
                @change="change"
                size="large">
                    <el-option v-for="item in state.industryTags" :key="item" :label="item" :value="item" />
                </el-select>
                <el-text> 数量：{{ state.data.length }} </el-text>
            </el-col>
            <el-col :span="4">
                <a :href="downloadUrl"><el-button type="success">下载</el-button></a>
            </el-col>
            <CopyStocksToClipboard :data="state.data" ></CopyStocksToClipboard>
        </el-row>

        <el-table :data="state.data" height="900" 
        :cell-class-name="tableCellClassName"
        @sort-change="sortChange"
        @cell-click="industryClick"
        :default-sort="state.sort"
        style="width: 100%">
            <el-table-column prop="stock" label="股票" width="150">
                <template #default="scope">
                    <ToStockDetail :stock="scope.row.stock" />
                </template> 
            </el-table-column>
            <el-table-column prop="wugu" label="吾股" sortable width="100"/>
            <el-table-column prop="industry" label="行业" sortable width="150"/>
            <el-table-column prop="industryRank" label="行业排名" width="100"/>
            <el-table-column prop="lp" label="分位点" sortable width="80"/>
            <el-table-column prop="relLp" label="相对分位点" sortable width="80"/>
            <el-table-column prop="lpDecrease" label="lpDecrease" sortable width="80"/>
            <el-table-column prop="lpDuration" label="持续月数" sortable width="80"/>
            <el-table-column prop="peRatio" label="PE" width="100" sortable />
            <el-table-column prop="pbRatio" label="PB" width="100" sortable />
            <el-table-column prop="dividendYield" label="股息" sortable width="100"/>
            <el-table-column prop="marketValue" label="总市值(亿)" width="160" sortable/>
            <el-table-column prop="circulationMarketValue" label="流通市值(亿)" width="160" sortable/>
            <el-table-column prop="updateTime" label="更新时间" width="180"/>
        </el-table>
    </div>
</template>

<script setup>
import { computed, reactive } from 'vue';
import { getWuguData } from '../service/wugu'
import ToStockDetail from './ToStockDetail.vue';
import { getHost } from '../utils/config';
import { getLpClassName } from '../utils/help';
import { getSessionStorage, setSessionStorage } from '../utils/help';
import CopyStocksToClipboard from './CopyStocksToClipboard.vue';
import { useRouteQuery } from '../utils/useRoute';

const baseKey = "wugu"
const selectKey = baseKey + "Select"
const sortPropKey = baseKey + "SortProp"
const sortOrderKey = baseKey + "SortOrder"

const state = reactive({
    rawData: [],
    data: [],
    industryTags: new Set(),
    selected: getSessionStorage(selectKey) || '全部',
    sort: { 
        prop: getSessionStorage(sortPropKey) || '' , 
        order: getSessionStorage(sortOrderKey) || '' 
    }
})

const downloadUrl = computed(() => {
    return getHost() +'/wugu/export'
})

let stocks = useRouteQuery("stocks", "")

getWuguData().then( res => {
    state.rawData = res.data
    if (stocks) {
        let stocksArr = stocks.split(";")
        state.rawData = state.rawData.filter(item => stocksArr.includes(item.stock))
    }

    state.industryTags.add("全部")
    state.rawData.forEach(item => {
        state.industryTags.add(item.industry)
        item.marketValue = formatMarketValue(item.marketValue)
        item.circulationMarketValue = formatMarketValue(item.circulationMarketValue)
    })
    change()
})

const change = () => {
    if (state.selected === "全部") {
        state.data = state.rawData
    } else {
        state.data = state.rawData.filter(item => item.industry === state.selected)
    }

    setSessionStorage(selectKey, state.selected)
}

const sortChange = (column, prop, order) => {
    setSessionStorage(sortPropKey, column.prop)
    setSessionStorage(sortOrderKey, column.order)
}

const industryClick = (row, column, cell, event) => {
    var columnProperty = column.property
    if (columnProperty == "industry") {
        // 还原
        if (state.selected === row.industry) {
            state.selected = "全部"
        } else {
            state.selected = row.industry
        }
        
        change()
    }
}

const tableCellClassName = ({row, column, rowIndex, columnIndex}) => {

    let columnProperty = column.property
    let val = row[columnProperty]
    if (columnProperty == "lp") {
        return getLpClassName(val)
    }

    if (columnProperty == "pbRatio") {
        if (val < 1) {
            return 'pctlt0-cell'
        }
    }

    if (columnProperty == "dividendYield") {
        if (val >= 3) {
            return 'lpgt99-cell'
        }
    }

    if (columnProperty == "relLp") {
        if (val <= 1) {
            return 'rellplt1-cell'
        }
    }

    if (columnProperty == "industryRank") {
        if (val == 1) {
            return 'd300up-cell'
        }
    }

    if (["closeRank", "moneyRank", "volumeRank"].includes(columnProperty)) {
        if (val >= 700) {
            return 'rank-gt700-cell'
        } 

        if (val <= 50) {
            return 'rank-lt50-cell'
        } 
    }

    return ''
}

const formatMarketValue = (rawMarketValue) => {
    let formated = 0
    if (!rawMarketValue) {
        return 0
    }

    if  (rawMarketValue.endsWith('万亿')) {
        formated =  Number(rawMarketValue.replace('万亿', '')) * 10000
    } else  {
        formated = Number(rawMarketValue.replace('亿', ''))
    }

    return Math.round(100 * formated) / 100
}
</script>

<style>
</style>